package com.rainng.coursesystem.repository;

import com.rainng.coursesystem.model.FavouriteItem;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Repository
public interface FavouriteRepository extends JpaRepository<FavouriteItem, String> {

    @Query("SELECT f FROM FavouriteItem f WHERE (:sNumber IS NULL OR f.sNumber = :sNumber) AND (:tNumber IS NULL OR f.tNumber = :tNumber)")
    List<FavouriteItem> findBysNumberOrtNumber(String sNumber, String tNumber);

    @Query("SELECT f FROM FavouriteItem f WHERE (:sNumber IS NULL OR f.sNumber <> :sNumber) AND (:tNumber IS NULL OR f.tNumber <> :tNumber) AND f.isPublic = true")
    List<FavouriteItem> findPublicFavouritesExcludingUser(String sNumber, String tNumber);

    @Query("SELECT f FROM FavouriteItem f WHERE f.sNumber IN :sNumbers OR f.tNumber IN :tNumbers")
    List<FavouriteItem> findBySNumberInOrTNumberIn(List<String> sNumbers, List<String> tNumbers);

    Optional<FavouriteItem> findByFileId(UUID fileId);

    @Query("SELECT CASE WHEN COUNT(f) > 0 THEN true ELSE false END " +
            "FROM FavouriteItem f " +
            "WHERE f.sNumber = :sNumber " +
            "AND (:tNumber IS NULL OR f.tNumber = :tNumber) " +
            "AND f.fileName = :fileName")
    boolean existsBysNumberAndFileName(@Param("sNumber") String sNumber, @Param("tNumber") String tNumber, @Param("fileName") String fileName);
}
